package com.pengy.shengxian.controller;

import com.pengy.shengxian.service.BjdInfoService;
import com.pengy.shengxian.service.DeliveryOrderService;
import com.pengy.shengxian.service.ExcelService;
import com.pengy.shengxian.service.GoodsInfoService;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.stage.FileChooser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Component
public class MainController {

    private static final Logger logger = LoggerFactory.getLogger(MainController.class);

    // 配送单导入相关控件
    @FXML private Label deliveryStatusLabel;
    @FXML private Label deliveryProgressLabel;
    @FXML private Label deliveryFileCountLabel;
    @FXML private ListView<String> deliveryFileListView;
    @FXML private TextArea deliveryResultTextArea;
    @FXML private ComboBox<String> deliveryCustomerComboBox;

    // 采购单导入相关控件
    @FXML private Label goodsTypeStatusLabel;
    @FXML private Label goodsTypeProgressLabel;
    @FXML private Label goodsTypeFileCountLabel;
    @FXML private ListView<String> goodsTypeFileListView;
    @FXML private TextArea goodsTypeResultTextArea;

    // 商品信息导入相关控件
    @FXML private Label goodsInfoStatusLabel;
    @FXML private Label goodsInfoProgressLabel;
    @FXML private Label goodsInfoFileCountLabel;
    @FXML private ListView<String> goodsInfoFileListView;
    @FXML private TextArea goodsInfoResultTextArea;

    // 报价单导入相关控件
    @FXML private Label bjdStatusLabel;
    @FXML private Label bjdProgressLabel;
    @FXML private Label bjdFileCountLabel;
    @FXML private ListView<File> bjdFileListView;
    @FXML private TextArea bjdResultTextArea;

    // 主选项卡
    @FXML private TabPane mainTabPane;

    @Autowired
    private ExcelService excelService;

    @Autowired
    private GoodsInfoService goodsInfoService;

    @Autowired
    private DeliveryOrderService deliveryOrderService;

    @Autowired private BjdInfoService bjdInfoService;

    // 配送单相关数据
    private ObservableList<String> deliveryFilePathList;
    private ObservableList<File> deliveryFileList;

    // 采购单相关数据
    private ObservableList<String> goodsTypeFilePathList;
    private ObservableList<File> goodsTypeFileList;

    // 商品信息相关数据
    private ObservableList<String> goodsInfoFilePathList;
    private ObservableList<File> goodsInfoFileList;

    // 报价单相关数据
    private ObservableList<String> bjdFilePathList = FXCollections.observableArrayList();
    private ObservableList<File> bjdFileList = FXCollections.observableArrayList();

    // 新增：保存最近一次合并导入的主表单号
    private String lastImportedPsdNo = null;

    @FXML
    public void initialize() {
        logger.info("初始化主控制器");

        // 初始化配送单相关数据
        deliveryFileList = FXCollections.observableArrayList();
        deliveryFilePathList = FXCollections.observableArrayList();
        deliveryFileListView.setItems(deliveryFilePathList);

        // 初始化采购单相关数据
        goodsTypeFileList = FXCollections.observableArrayList();
        goodsTypeFilePathList = FXCollections.observableArrayList();
        goodsTypeFileListView.setItems(goodsTypeFilePathList);

        // 初始化商品信息相关数据
        goodsInfoFileList = FXCollections.observableArrayList();
        goodsInfoFilePathList = FXCollections.observableArrayList();
        if (goodsInfoFileListView != null) {
            goodsInfoFileListView.setItems(goodsInfoFilePathList);
        }

        // 初始化报价单相关数据
        bjdFileList = FXCollections.observableArrayList();
        bjdFilePathList = FXCollections.observableArrayList();
        if (bjdFileListView != null) {
            bjdFileListView.setItems(bjdFileList);
        }

        // 初始化配送单客户下拉框（键值对显示，值为T002/T003）
        if (deliveryCustomerComboBox != null) {
            javafx.util.StringConverter<javafx.util.Pair<String, String>> converter = new javafx.util.StringConverter<javafx.util.Pair<String, String>>() {
                @Override
                public String toString(javafx.util.Pair<String, String> object) {
                    return object == null ? "" : object.getKey() + ":" + object.getValue();
                }
                @Override
                public javafx.util.Pair<String, String> fromString(String string) {
                    if (string == null || !string.contains(":")) return null;
                    String[] arr = string.split(":");
                    return new javafx.util.Pair<>(arr[0], arr[1]);
                }
            };
            javafx.collections.ObservableList<javafx.util.Pair<String, String>> customerOptions = javafx.collections.FXCollections.observableArrayList();
            customerOptions.add(new javafx.util.Pair<>("联通省分公司", "T002"));
            customerOptions.add(new javafx.util.Pair<>("联通合肥分公司", "T003"));
            deliveryCustomerComboBox.setConverter(new javafx.util.StringConverter<String>() {
                @Override
                public String toString(String value) {
                    if (value == null) return "";
                    if ("T002".equals(value)) return "联通省分公司:T002";
                    if ("T003".equals(value)) return "联通合肥分公司:T003";
                    return value;
                }
                @Override
                public String fromString(String string) {
                    if (string == null) return null;
                    if (string.contains(":")) return string.split(":")[1];
                    return string;
                }
            });
            deliveryCustomerComboBox.getItems().addAll("T002", "T003");
            deliveryCustomerComboBox.setValue("T002");
        }

        // 初始化状态
        updateDeliveryStatus("就绪");
        updateGoodsTypeStatus("就绪");
        updateGoodsInfoStatus("就绪");
        updateBjdStatus("就绪");

        updateDeliveryFileCount();
        updateGoodsTypeFileCount();
        updateGoodsInfoFileCount();
        updateBjdFileCount();

        // 页面初始化时自动最大化窗口（加判空保护）
        javafx.application.Platform.runLater(() -> {
            if (mainTabPane != null && mainTabPane.getScene() != null && mainTabPane.getScene().getWindow() != null) {
                javafx.stage.Window window = mainTabPane.getScene().getWindow();
                if (window instanceof javafx.stage.Stage) {
                    javafx.stage.Stage stage = (javafx.stage.Stage) window;
                    stage.setMaximized(true);
                }
            }
        });

        logger.info("主控制器初始化完成");
    }

    /**
     * 初始化商品信息表格列
     */
    private void initializeGoodsInfoTableColumns() {
        // 移除: goodsInfoDataTableView.getColumns().addAll(...)
    }

    // ==================== 配送单导入功能 ====================

    @FXML
    private void handleImportDeliveryOrders() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择配送单Excel文件");
        fileChooser.getExtensionFilters().addAll(
            new FileChooser.ExtensionFilter("Excel文件", "*.xlsx", "*.xls"),
            new FileChooser.ExtensionFilter("所有文件", "*.*")
        );

        List<File> selectedFiles = fileChooser.showOpenMultipleDialog(deliveryResultTextArea.getScene().getWindow());

        if (selectedFiles != null && !selectedFiles.isEmpty()) {
            logger.info("用户选择了 {} 个配送单文件", selectedFiles.size());

            for (File file : selectedFiles) {
                String filePath = file.getAbsolutePath();
                if (!deliveryFilePathList.contains(filePath)) {
                    deliveryFileList.add(file);
                    deliveryFilePathList.add(filePath);
                    logger.info("添加配送单文件: {}", file.getName());
                } else {
                    logger.info("配送单文件已存在，跳过: {}", file.getName());
                }
            }

            updateDeliveryFileCount();
            updateDeliveryStatus("已选择 " + selectedFiles.size() + " 个配送单文件，等待处理");
        } else {
            logger.info("用户取消了配送单文件选择");
        }
    }

    @FXML
    private void handleStartProcessing() {
        if (deliveryFileList.isEmpty()) {
            showAlert("请先选择要处理的配送单Excel文件", Alert.AlertType.WARNING);
            return;
        }
        // 获取客户编码
        String psdDept = deliveryCustomerComboBox.getValue();
        try {
            updateDeliveryStatus("开始处理配送单文件...");
            if (deliveryResultTextArea != null) deliveryResultTextArea.clear();
            List<File> fileList = new ArrayList<>(deliveryFileList);
            // 调用后端批量处理，每个文件独立结果
            List<com.pengy.shengxian.service.DeliveryOrderService.DeliveryOrderProcessResult> results = deliveryOrderService.processDeliveryOrderExcel(fileList, psdDept);
            StringBuilder resultText = new StringBuilder();
            int totalSuccess = 0, totalError = 0, totalDetail = 0;
            for (int i = 0; i < fileList.size(); i++) {
                File file = fileList.get(i);
                com.pengy.shengxian.service.DeliveryOrderService.DeliveryOrderProcessResult r = results.get(i);
                resultText.append(r.getTextResult(file.getName())).append("\n");
                if (r.getErrorCount() > 0) totalError++;
                else {
                    totalSuccess++;
                    totalDetail += r.getDetailCount();
                }
            }
            if (deliveryResultTextArea != null) {
                deliveryResultTextArea.setText(resultText.toString());
            }
            updateDeliveryStatus(String.format("处理完成: 总数=%d, 成功=%d, 失败=%d, 明细总数=%d", fileList.size(), totalSuccess, totalError, totalDetail));
            showAlert(String.format("配送单导入完成！\n总计: %d 个文件\n成功: %d\n失败: %d", fileList.size(), totalSuccess, totalError),
                totalError > 0 ? Alert.AlertType.WARNING : Alert.AlertType.INFORMATION);
            // 处理完成后清空待处理文件列表
            deliveryFileList.clear();
            deliveryFilePathList.clear();
            updateDeliveryFileCount();
        } catch (Exception e) {
            logger.error("处理配送单文件时发生错误", e);
            updateDeliveryStatus("处理失败: " + e.getMessage());
            showAlert("处理配送单文件时发生错误: " + e.getMessage(), Alert.AlertType.ERROR);
        }
    }

    // ==================== 采购单导入功能 ====================

    @FXML
    private void handleImportGoodsType() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择采购单Excel文件");
        fileChooser.getExtensionFilters().addAll(
            new FileChooser.ExtensionFilter("Excel文件", "*.xlsx", "*.xls"),
            new FileChooser.ExtensionFilter("所有文件", "*.*")
        );

        List<File> selectedFiles = fileChooser.showOpenMultipleDialog(goodsTypeResultTextArea.getScene().getWindow());

        if (selectedFiles != null && !selectedFiles.isEmpty()) {
            logger.info("用户选择了 {} 个采购单文件", selectedFiles.size());

            for (File file : selectedFiles) {
                String filePath = file.getAbsolutePath();
                if (!goodsTypeFilePathList.contains(filePath)) {
                    goodsTypeFileList.add(file);
                    goodsTypeFilePathList.add(filePath);
                    logger.info("添加采购单文件: {}", file.getName());
                } else {
                    logger.info("采购单文件已存在，跳过: {}", file.getName());
                }
            }

            updateGoodsTypeFileCount();
            updateGoodsTypeStatus("已选择 " + selectedFiles.size() + " 个采购单文件，等待处理");
        } else {
            logger.info("用户取消了采购单文件选择");
        }
    }

    @FXML
    private void handleStartGoodsTypeProcessing() {
        if (goodsTypeFileList.isEmpty()) {
            showAlert("请先选择要处理的采购单Excel文件", Alert.AlertType.WARNING);
            return;
        }

        try {
            updateGoodsTypeStatus("开始处理采购单文件...");
            goodsTypeProgressLabel.setText("处理中...");

            goodsTypeResultTextArea.clear(); // 清空文本区域

            int totalProcessed = 0;
            int totalSuccess = 0;
            int totalError = 0;
            StringBuilder resultText = new StringBuilder(); // 用于构建结果文本

            for (File file : goodsTypeFileList) {
                logger.info("开始处理采购单文件: {}", file.getName());
                goodsTypeProgressLabel.setText("处理文件: " + file.getName());

                try {
                    // 调用采购单处理服务
                    DeliveryOrderService.ProcurementOrderProcessResult result = deliveryOrderService.processProcurementOrderExcel(file);

                    totalProcessed += result.getTotalCount();
                    totalSuccess += result.getSuccessCount();
                    totalError += result.getErrorCount();

                    // 构建处理结果文本
                    if (result.getErrorMessage() != null && !result.getErrorMessage().isEmpty()) {
                        // 处理失败
                        resultText.append(String.format("%s处理失败，原因：%s\n", file.getName(), result.getErrorMessage()));
                    } else {
                        // 处理成功
                        if (result.getProcessedData() != null && !result.getProcessedData().isEmpty()) {
                            for (Object data : result.getProcessedData()) {
                                if (data instanceof com.pengy.shengxian.entity.CgdInfo) {
                                    com.pengy.shengxian.entity.CgdInfo cgdInfo = (com.pengy.shengxian.entity.CgdInfo) data;
                                    resultText.append(String.format("%s处理成功，单号：%s，导入%d条商品明细\n",
                                        file.getName(), cgdInfo.getCgdCode(), result.getDetailCount()));
                                }
                            }
                        } else {
                            resultText.append(String.format("%s处理成功，但未找到有效数据\n", file.getName()));
                        }
                    }

                    // 如果有错误，显示错误信息
                    if (result.getErrorMessage() != null && !result.getErrorMessage().isEmpty()) {
                        showAlert("文件 " + file.getName() + " 处理时出现问题: " + result.getErrorMessage(),
                                Alert.AlertType.WARNING);
                    }

                    logger.info("采购单文件 {} 处理完成: 总数={}, 成功={}, 失败={}, 明细数量={}",
                               file.getName(), result.getTotalCount(), result.getSuccessCount(),
                               result.getErrorCount(), result.getDetailCount());

                } catch (Exception e) {
                    logger.error("处理采购单文件 {} 时发生错误", file.getName(), e);
                    resultText.append(String.format("%s处理失败，原因：%s\n", file.getName(), e.getMessage()));
                    showAlert("处理文件 " + file.getName() + " 时发生错误: " + e.getMessage(),
                            Alert.AlertType.ERROR);
                    totalError++;
                }
            }

            // 显示处理结果文本
            goodsTypeResultTextArea.setText(resultText.toString());

            // 更新状态
            String statusMessage = String.format("处理完成: 总数=%d, 成功=%d, 失败=%d",
                                               totalProcessed, totalSuccess, totalError);
            updateGoodsTypeStatus(statusMessage);
            goodsTypeProgressLabel.setText("处理完成");

            // 清空文件列表
            goodsTypeFileList.clear();
            goodsTypeFilePathList.clear();
            updateGoodsTypeFileCount();

            if (totalError > 0) {
                showAlert("处理完成，但有 " + totalError + " 个文件处理失败", Alert.AlertType.WARNING);
            } else {
                showAlert(String.format("采购单导入完成！\n总计处理: %d 个文件\n成功导入: %d 个采购单",
                    totalProcessed, totalSuccess),
                    Alert.AlertType.INFORMATION);
            }

        } catch (Exception e) {
            logger.error("处理采购单文件时发生错误", e);
            updateGoodsTypeStatus("处理失败: " + e.getMessage());
            goodsTypeProgressLabel.setText("处理失败");
            showAlert("处理采购单文件时发生错误: " + e.getMessage(), Alert.AlertType.ERROR);
        }
    }

    // ==================== 商品信息导入功能 ====================

    @FXML
    private void handleImportGoodsInfo() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择商品信息Excel文件");
        fileChooser.getExtensionFilters().addAll(
            new FileChooser.ExtensionFilter("Excel文件", "*.xlsx", "*.xls"),
            new FileChooser.ExtensionFilter("所有文件", "*.*")
        );

        List<File> selectedFiles = fileChooser.showOpenMultipleDialog(goodsInfoResultTextArea.getScene().getWindow());

        if (selectedFiles != null && !selectedFiles.isEmpty()) {
            logger.info("用户选择了 {} 个商品信息文件", selectedFiles.size());

            for (File file : selectedFiles) {
                String filePath = file.getAbsolutePath();
                if (!goodsInfoFilePathList.contains(filePath)) {
                    goodsInfoFileList.add(file);
                    goodsInfoFilePathList.add(filePath);
                    logger.info("添加商品信息文件: {}", file.getName());
                } else {
                    logger.info("商品信息文件已存在，跳过: {}", file.getName());
                }
            }

            updateGoodsInfoFileCount();
            updateGoodsInfoStatus("已选择 " + selectedFiles.size() + " 个商品信息文件，等待处理");
        } else {
            logger.info("用户取消了商品信息文件选择");
        }
    }

    @FXML
    private void handleStartGoodsInfoProcessing() {
        if (goodsInfoFileList.isEmpty()) {
            showAlert("请先选择要处理的商品信息Excel文件", Alert.AlertType.WARNING);
            return;
        }
        // 新增导入确认弹窗
        Alert confirmAlert = new Alert(Alert.AlertType.CONFIRMATION);
        confirmAlert.setTitle("导入确认");
        confirmAlert.setHeaderText(null);
        confirmAlert.setContentText("导入后将会覆盖原有的商品信息，请确认是否导入？");
        java.util.Optional<ButtonType> result = confirmAlert.showAndWait();
        if (!result.isPresent() || result.get() != ButtonType.OK) {
            return;
        }
        try {
            updateGoodsInfoStatus("开始处理商品信息文件...");
            goodsInfoProgressLabel.setText("处理中...");
            int totalProcessed = 0;
            int totalSuccess = 0;
            int totalError = 0;
            StringBuilder resultText = new StringBuilder();
            for (File file : goodsInfoFileList) {
                logger.info("开始处理商品信息文件: {}", file.getName());
                goodsInfoProgressLabel.setText("处理文件: " + file.getName());
                try {
                    GoodsInfoService.GoodsInfoProcessResult processResult = goodsInfoService.processGoodsInfoExcel(file);
                    totalProcessed += processResult.getTotalCount();
                    totalSuccess += processResult.getSuccessCount();
                    totalError += processResult.getErrorCount();
                    if (processResult.getErrorMessage() != null && !processResult.getErrorMessage().isEmpty()) {
                        resultText.append(String.format("%s处理失败，原因：%s；\n", file.getName(), processResult.getErrorMessage()));
                    } else {
                        resultText.append(String.format("%s处理成功，导入%d条商品明细；\n", file.getName(), processResult.getSuccessCount()));
                    }
                } catch (Exception e) {
                    logger.error("处理商品信息文件 {} 时发生错误", file.getName(), e);
                    resultText.append(String.format("%s处理失败，原因：%s；\n", file.getName(), e.getMessage()));
                    totalError++;
                }
            }
            goodsInfoResultTextArea.setText(resultText.toString());
            String statusMessage = String.format("处理完成: 总数=%d, 成功=%d, 失败=%d", totalProcessed, totalSuccess, totalError);
            updateGoodsInfoStatus(statusMessage);
            goodsInfoProgressLabel.setText("处理完成");
            if (totalError > 0) {
                showAlert("处理完成，但有 " + totalError + " 个文件处理失败", Alert.AlertType.WARNING);
            } else {
                showAlert("所有文件处理成功！", Alert.AlertType.INFORMATION);
            }
        } catch (Exception e) {
            logger.error("处理商品信息文件时发生错误", e);
            updateGoodsInfoStatus("处理失败: " + e.getMessage());
            goodsInfoProgressLabel.setText("处理失败");
            showAlert("处理商品信息文件时发生错误: " + e.getMessage(), Alert.AlertType.ERROR);
        }
    }

    // ==================== 报价单导入功能 ====================

    @FXML
    private void handleImportBjd() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择报价单Excel文件");
        fileChooser.getExtensionFilters().addAll(
            new FileChooser.ExtensionFilter("Excel文件", "*.xlsx", "*.xls"),
            new FileChooser.ExtensionFilter("所有文件", "*.*")
        );
        List<File> selectedFiles = fileChooser.showOpenMultipleDialog(bjdResultTextArea.getScene().getWindow());
        if (selectedFiles != null && !selectedFiles.isEmpty()) {
            for (File file : selectedFiles) {
                String filePath = file.getAbsolutePath();
                if (!bjdFilePathList.contains(filePath)) {
                    bjdFileList.add(file);
                    bjdFilePathList.add(filePath);
                }
            }
            updateBjdFileCount();
            updateBjdStatus("已选择 " + selectedFiles.size() + " 个报价单文件，等待处理");
        }
    }
    @FXML
    private void handleStartBjdProcessing() {
        if (bjdFileList.isEmpty()) {
            showAlert("请先选择要处理的报价单Excel文件", Alert.AlertType.WARNING);
            return;
        }
        try {
            updateBjdStatus("开始处理报价单文件...");
            bjdProgressLabel.setText("处理中...");
            bjdResultTextArea.clear();
            int totalProcessed = 0;
            int totalSuccess = 0;
            int totalError = 0;
            StringBuilder resultText = new StringBuilder();
            for (File file : bjdFileList) {
                bjdProgressLabel.setText("处理文件: " + file.getName());
                try {
                    int detailCount = bjdInfoService.importBjdExcelWithDetailCount(file);
                    totalProcessed++;
                    totalSuccess++;
                    resultText.append(String.format("%s处理成功，导入%d条商品明细;\n", file.getName(), detailCount));
                } catch (Exception e) {
                    logger.error("处理报价单文件 {} 时发生异常", file.getName(), e);
                    resultText.append(String.format("%s处理失败，原因：%s;\n", file.getName(), e.getMessage()));
                    showAlert("处理文件 " + file.getName() + " 时发生错误: " + e.getMessage(), Alert.AlertType.ERROR);
                    totalError++;
                }
            }
            bjdResultTextArea.setText(resultText.toString());
            String statusMessage = String.format("处理完成: 总数=%d, 成功=%d, 失败=%d", totalProcessed, totalSuccess, totalError);
            updateBjdStatus(statusMessage);
            bjdProgressLabel.setText("处理完成");
            bjdFileList.clear();
            bjdFilePathList.clear();
            updateBjdFileCount();
            if (totalError > 0) {
                showAlert("处理完成，但有 " + totalError + " 个文件处理失败", Alert.AlertType.WARNING);
            } else {
                showAlert(String.format("报价单导入完成！\n总计处理: %d 个文件\n成功导入: %d 个报价单", totalProcessed, totalSuccess), Alert.AlertType.INFORMATION);
            }
        } catch (Exception e) {
            logger.error("处理报价单文件时发生异常", e);
            updateBjdStatus("处理失败: " + e.getMessage());
            bjdProgressLabel.setText("处理失败");
            showAlert("处理报价单文件时发生错误: " + e.getMessage(), Alert.AlertType.ERROR);
        }
    }

    // ==================== 辅助方法 ====================

    private void updateDeliveryFileCount() {
        int count = deliveryFileList.size();
        deliveryFileCountLabel.setText("(" + count + "个文件)");
    }

    private void updateGoodsTypeFileCount() {
        int count = goodsTypeFileList.size();
        goodsTypeFileCountLabel.setText("(" + count + "个文件)");
    }

    private void updateGoodsInfoFileCount() {
        int count = goodsInfoFileList.size();
        goodsInfoFileCountLabel.setText("(" + count + "个文件)");
    }

    private void updateBjdFileCount() {
        bjdFileCountLabel.setText(String.format("(%d个文件)", bjdFileList.size()));
        bjdFileListView.setItems(bjdFileList);
    }

    private void updateDeliveryStatus(String status) {
        deliveryStatusLabel.setText(status);
        logger.info("配送单状态更新: {}", status);
    }

    private void updateGoodsTypeStatus(String status) {
        goodsTypeStatusLabel.setText(status);
        logger.info("采购单状态更新: {}", status);
    }

    private void updateGoodsInfoStatus(String status) {
        goodsInfoStatusLabel.setText(status);
        logger.info("商品信息状态更新: {}", status);
    }

    private void updateBjdStatus(String status) {
        bjdStatusLabel.setText(status);
    }

    private void showAlert(String message, Alert.AlertType alertType) {
        Alert alert = new Alert(alertType);
        alert.setTitle("提示");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    @FXML
    private void handleExportDeliveryOrders() {
        // 构建弹窗
        Dialog<ButtonType> dialog = new Dialog<>();
        dialog.setTitle("导出配送单");
        dialog.setHeaderText("请选择导出条件");

        // 日期选择器
        DatePicker datePicker = new DatePicker(java.time.LocalDate.now());
        datePicker.setPromptText("请选择配送日期");

        // 客户下拉框
        ComboBox<String> customerComboBox = new ComboBox<>();
        customerComboBox.getItems().addAll("联通省分公司:T002", "联通合肥分公司:T003");
        customerComboBox.setValue("联通省分公司:T002");

        // 布局
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.add(new Label("配送日期:"), 0, 0);
        grid.add(datePicker, 1, 0);
        grid.add(new Label("客户:"), 0, 1);
        grid.add(customerComboBox, 1, 1);

        dialog.getDialogPane().setContent(grid);
        dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);

        Optional<ButtonType> result = dialog.showAndWait();
        if (result.isPresent() && result.get() == ButtonType.OK) {
            java.time.LocalDate selectedDate = datePicker.getValue();
            String customerValue = customerComboBox.getValue();
            if (selectedDate == null || customerValue == null || customerValue.isEmpty()) {
                showAlert("请选择配送日期和客户！", Alert.AlertType.WARNING);
                return;
            }
            String psdDept = customerValue.split(":")[1];
            java.sql.Date date = java.sql.Date.valueOf(selectedDate);

            // 查询主表单号
            java.util.List<String> psdHjkCodeList = deliveryOrderService.getPsdHjkCodesByDeptAndDate(psdDept, date);
            if (psdHjkCodeList == null || psdHjkCodeList.isEmpty()) {
                showAlert("未找到符合条件的配送单！", Alert.AlertType.WARNING);
                return;
            }

            // 选择导出文件夹
            javafx.stage.DirectoryChooser directoryChooser = new javafx.stage.DirectoryChooser();
            directoryChooser.setTitle("选择导出文件夹");
            java.io.File selectedDir = directoryChooser.showDialog(mainTabPane.getScene().getWindow());
            if (selectedDir != null) {
                try {
                    deliveryOrderService.exportDeliveryOrdersToExcel(selectedDir, psdHjkCodeList);
                    showAlert("配送单导出成功！", Alert.AlertType.INFORMATION);
                } catch (Exception e) {
                    showAlert("配送单导出失败：" + e.getMessage(), Alert.AlertType.ERROR);
                }
            }
        }
    }
}